package scripts

import (
	"bytes"
	"fmt"
	"log"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
)

type CallScript struct {
	workDir    string
	runScripts [][]string
}

func (c *CallScript) base() string {
	return filepath.Clean(c.workDir)
}
func (c *CallScript) execScript() {
	for i := range c.runScripts {
		cmd := c.runScripts[i][0]
		params := c.runScripts[i][1]
		execCmd(cmd, params)
	}
}

func execCmd(command string, params ...string) {
	cmd := exec.Command(command, params...)
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout // 标准输出
	cmd.Stderr = &stderr // 标准错误
	err := cmd.Run()
	outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())
	fmt.Printf("out:\n%s\nerr:\n%s\n", outStr, errStr)
	if err != nil {
		log.Fatalf("cmd.Run() failed with %s\n", err)
	}
}

type callScriptType uint32

const (
	Crop_256 callScriptType = iota
	Crop_512
	Extcrop_256
	Extcrop_512
	Resize_256
	Resize_512
	Full_256
	Full_512
	Extfull_256
	Extfull_512
	Enhancer_gfpgan_256
	Enhancer_gfpgan_512
	Enhancer_gfpgan_still_256
	Enhancer_gfpgan_still_512
)

func (c callScriptType) ToScript(workDir, audioFile, imageFile, resultDir string) *CallScript {
	script := fmt.Sprintf("%s --driven_audio %s --source_image %s --result_dir %s",
		c.string(), audioFile, imageFile, resultDir)
	var commands [][]string
	//commands = append(commands, []string{"cd", "./"})
	commands = append(commands, strings.Split(script, " "))
	return &CallScript{
		workDir:    workDir,
		runScripts: commands,
	}
}
func (c callScriptType) string() string {
	switch c {
	case Crop_256:
		return "python inference.py --preprocess crop --size 256"
	case Crop_512:
		return "python inference.py --preprocess crop --size 512"
	case Extcrop_256:
		return "python inference.py --preprocess extcrop --size 256"
	case Extcrop_512:
		return "python inference.py --preprocess extcrop --size 512"
	case Resize_256:
		return "python inference.py --preprocess resize --size 256"
	case Resize_512:
		return "python inference.py --preprocess resize --size 512"
	case Full_256:
		return "python inference.py --preprocess full --size 256"
	case Full_512:
		return "python inference.py --preprocess full --size 512"
	case Extfull_256:
		return "python inference.py --preprocess extfull --size 256"
	case Extfull_512:
		return "python inference.py --preprocess extfull --size 512"
	case Enhancer_gfpgan_256:
		return "python inference.py --preprocess full --size 256 --enhancer gfpgan"
	case Enhancer_gfpgan_512:
		return "python inference.py --preprocess full --size 512 --enhancer gfpgan"
	case Enhancer_gfpgan_still_256:
		return "python inference.py --preprocess full --size 256 --enhancer gfpgan --still"
	case Enhancer_gfpgan_still_512:
		return "python inference.py --preprocess full --size 512 --enhancer gfpgan --still"
	default:
		return "callScriptType(" + strconv.FormatInt(int64(c), 10) + ")"
	}
}
